package net.mcreator.makecustomitem;

import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;
import com.google.common.collect.ImmutableMap;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttribute;
import net.minecraft.entity.ai.attributes.IAttributeInstance;

public class AttrHelper {

	public static final UUID MAX_HEALTH_MODIFIER_UUID = UUID.fromString("9582029a-96db-476d-95f1-3b6cd0f346fc");
	public static final UUID ATTACK_DAMAGE_MODIFIER_UUID = UUID.fromString("bd598b08-4e85-4a99-8085-31f9b02a21d1");
	public static final Map<String, BiConsumer<EntityLivingBase, Float>> OPERATIONS = new ImmutableMap.Builder<String, BiConsumer<EntityLivingBase, Float>>()
			.put("sethealth", (living, count) -> {
				living.setHealth(count);
			}).put("addhealth", (living, count) -> {
				living.setHealth(living.getHealth() + count);
			}).put("addmaxhealth", (living, count) -> {
				changeAttr(living, SharedMonsterAttributes.MAX_HEALTH, MAX_HEALTH_MODIFIER_UUID, count, true);
				living.setHealth(Math.min(living.getHealth(), living.getMaxHealth()));
			}).put("setmaxhealth", (living, count) -> {
				changeAttr(living, SharedMonsterAttributes.MAX_HEALTH, MAX_HEALTH_MODIFIER_UUID, count, false);
				living.setHealth(Math.min(living.getHealth(), living.getMaxHealth()));
			}).put("addattack", (living, count) -> {
				changeAttr(living, SharedMonsterAttributes.ATTACK_DAMAGE, ATTACK_DAMAGE_MODIFIER_UUID, count, true);
			}).put("setattack", (living, count) -> {
				changeAttr(living, SharedMonsterAttributes.ATTACK_DAMAGE, ATTACK_DAMAGE_MODIFIER_UUID, count, false);
			}).build();

	private static void changeAttr(EntityLivingBase living, IAttribute attr, UUID uuid, double count, boolean add) {
		IAttributeInstance attrIns = living.getEntityAttribute(attr);
		AttributeModifier modifier = attrIns.getModifier(uuid);
		double oldModifirValue = 0;
		double oldAttrValue = attrIns.getAttributeValue();
		if (modifier != null) {
			oldModifirValue = modifier.getAmount();
			attrIns.removeModifier(uuid);
		}
		count += oldModifirValue;
		attrIns.applyModifier(new AttributeModifier(uuid, "modified by command", add ? count : count - oldAttrValue, 0)
				.setSaved(true));
	}
}
